package com.elm.controller;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.elm.entity.Business;
import com.elm.service.BusinessService;
import com.elm.service.impl.BusinessServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class BusinessController implements BaseController{

    private BusinessService businessService;

    public BusinessController() {
        businessService = new BusinessServiceImpl();
    }
    @Override
    public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String action = req.getPathInfo().split("/")[2];

        switch (action) {
            case "getBusinessById":
                getBusinessById(req, resp);
                break;
            case "listBusinessByOrderTypeId":
                getListFoodByOrderTypeId(req, resp);
                break;
        }
    }

    /**
     * 根据id查商家信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void getBusinessById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String businessId = req.getParameter("businessId");
        System.out.println("根据商家Id查询商家信息" + businessId);
        Business business = businessService.getBusinessById(Integer.parseInt(businessId));

        resp.setContentType("application/json;charset=UTF-8");
        if (business == null) {
            resp.getWriter().write("{\"error\":\"店铺ID错误\"}");
        }else {
            resp.getWriter().write(new Gson().toJson(business));
        }
    }



    private void getListFoodByOrderTypeId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String orderTypeId = req.getParameter("orderTypeId");
        System.out.println("根据点餐类型查询店铺信息");

        List<Business> list = businessService.getBusinessByOrderTypeId(orderTypeId);
        resp.setContentType("application/json;charset=UTF-8");

        if (list == null) {
            resp.getWriter().write("{\"error\":\"无相关的店铺信息\"}");
        }else {
            resp.getWriter().write(new Gson().toJson(list));
        }
    }
}